#!/usr/sbin/rsct/perl5/bin/perl 
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 1999,2002 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# "@(#)30   1.15   src/rsct/registry/cli/bin/rmsrcol.perl, srcli, rsct_rpyxh, rpyxht1f3 2/22/01 16:25:36"
######################################################################
#                                                                    #
# Module: rmsrcol                                                    #
#                                                                    #
# Purpose:                                                           #
#   rmsrcol - Removes columns from a System Registry table.          #
#                                                                    #
# Syntax:                                                            #
#   rmsrcol [-h][-TV] Table Column...                                #
#                                                                    #
# Flags:                                                             #
#   -h  help - writes this command's usage statement to stdout       #
#   -T  Trace - -writes this program's trace messages to stderr      #
#   -V  Verbose - writes this program's verbose messages to stderr   #
#                                                                    #
# Operands:                                                          #
#   Table   The name of the table that you wish to modify. The       #
#           Table can contain a relative or absolute path.           #
#   Column  Name of the column to be removed. More than one          #
#           Column operand can be specified. Names must match        #
#           one of the column names previously defined in the        #
#           specified table's metadata.                              #
#                                                                    #
# Description:                                                       #
#   The rmsrcol command removes one or more Columns from the         #
#   specified table in the System Registry. If the command is        #
#   successful all of the columns specified have been removed. If an #
#   error occurs you are guaranteed that none of the columns will    #
#   have been removed.                                               #
#                                                                    #
#   You are not permitted to remove the primary key or row change    #
#   counter columns of a table.                                      #
#                                                                    #
#   Use the lssrtbldef or lssrtbl command to get a current column    #
#   definition list.                                                 #
#                                                                    #
# Exit Values:                                                       #
#   0  SR_CLI_SUCCESS        Command completed successfully.         #
#   1  SR_CLI_REGISTRY_ERROR Command terminated due to an underlying #
#                            System Registry error.                  #
#   2  SR_CLI_ERROR          Command terminated due to an underlying #
#                            error in the command script.            #
#   3  SR_CLI_BAD_OPERAND    Command terminated due to user          #
#                            specifying a bad operand.               #
#   4  SR_CLI_BAD_FLAG       Command terminated due to user          #
#                            specifying an invalid flag.             #
#   5  SR_CLI_USER_ERROR     Command terminated due to a user error. #
#                            For example specifying an undefined     #
#                            table to be modified.                   #
#                                                                    #
# Examples:                                                          #
#   To remove 3 columns from the table 'table1'                      #
#   rmsrcol /temp/table1 col1 col2 col3                              #
#                                                                    #
#--------------------------------------------------------------------#
# Inputs:                                                            #
#                                                                    #
# Outputs:                                                           #
#   stdout - messages during execution and Verbose output            #
#   stderr - error messages                                          #
#                                                                    #
# External Ref:                                                      #
#   Commands: $LSMSG                                                 #
#   Extensions:  CT::SR.pm CT::SRrc.pm                               #
#   Perl library routines: Getopts::Std                              #
#   SR cli modules:    SR_cli_utils.pm - init_session error_exit     #
#       $DEFAULT_GLOBAL_MOUNT_POINT set_session_variables printCEMsg #
#                      SR_cli_rc - CLI return codes                  #
#                                                                    #
# Tab Settings:                                                      #
#   4 and tabs should be expanded to spaces before saving this file. #
#   in vi:  (:set ts=4  and   :%!expand -4)                          #
#                                                                    #
# Change Activity:                                                   #
#   000929 HGJ 38317: Initial delivery.                              #
#                                                                    #
######################################################################

#--------------------------------------------------------------------#
#                                                                    #
# General Program Flow/Logic:                                        #
#                                                                    #
# A: Parse command line - get table name and input file              #
# B: Initialise session with registry, including changing the        #
#    current directory if a relative path name is given (use value   #
#    given in CT_SR_HOME)                                            #
# C: Open file to be edited - exit if it won't open                  #
# D: Call CT::SR::delete_columns                                     #
# E: Close session table and tree                                    #
#                                                                    #
#--------------------------------------------------------------------#


#--------------------------------------------------------------------#
# Included libraries and extensions                                  #
#--------------------------------------------------------------------#
use lib "/usr/sbin/rsct/pm";
use locale;
use Getopt::Std;

use CT_cli_utils qw(printIMsg
                    printEMsg
);

use CT::SR;
use CT::SRrc;
use SR_cli_utils qw(init_session 
                    printCEMsg 
                    $DEFAULT_GLOBAL_MOUNT_POINT
                    open_table
                    set_session_variables
                    clean_session
                    error_exit
); 
use SR_cli_rc qw(:return_codes);


#--------------------------------------------------------------------#
# Global Variables                                                   #
#--------------------------------------------------------------------#
# Constants
$TRUE           = 1;
$FALSE          = 0;

# Other Globals
$Verbose        = $FALSE;
$Trace          = $FALSE;

# Messaging variables
$PROGNAME       = "rmsrcol";            # Program Name for messages
$MSGCAT         = "srcli.cat";          # msg catalogue for this cmd
$CTDIR          = "/usr/sbin/rsct";     # Cluster directory path
$CTBINDIR       = "$CTDIR/bin";         # Cluster Bin directory path
$LSMSG          = "$CTBINDIR/ctdspmsg"; # Display message routine

$ENV{'MSGMAPPATH'} = "$CTDIR/msgmaps"; # Msg map path used by $LSMSG  

%Cleanup = ();                            # Hash of items to cleanup
                                          # {Session} $session to term

#--------------------------------------------------------------------#
# Variables                                                          #
#--------------------------------------------------------------------#
# Variables for use with extension structures
my $Table_handle   = "";                # initialised in open_table
my $Tree_handle    = "";                # initialised in init_session

my $Table_name     = "";
my $Table          = "";
my $Set_work_dir   = $FALSE;
my $rc             = 0;                 # assume good return code

my $Mount_point    = $DEFAULT_GLOBAL_MOUNT_POINT;


#--------------------------------------------------------------------#
# Main Code                                                          #
#--------------------------------------------------------------------#
# TODO: Many verbose statements in this code will eventually by
# Trace statements when the facility is available as a Perl CLI
# (feature 48401)
# TODO: security on access to the table can not be further defined
# until after a security design has been implemented for the SR.
# ( feature 48402 ) Until then, the table is opened with the
# minimum security necessary to complete the command.


# Parse the command line, exit if there are errors
($rc, $Table_name) = parse_cmd_line();  
($rc == 0) || error_exit($rc);

# Verbose statement to echo the command line input
if ($Verbose) {
    foreach (@ARGV) { $output_string .= "  $_\n"; }
    $output_string = "\'  $Table_name\n$output_string\n\'";
    printIMsg("IMsgrmsrcolCommandLineInput", $output_string);
}
    

# Initialize Registry Library Connection
($Set_work_dir, $Table) = set_session_variables($Table_name);
($rc, $Tree_handle) = init_session($Set_work_dir);
($rc == 0) || error_exit($rc);

# Flag the session as needing to be cleaned up
$Cleanup{Session} = $Tree_handle;

$Verbose && 
    printIMsg("IMsgrmsrcolRemovingColumns", $Table_name, $Table);


# Open the table to be edited
($rc, $Table_handle) = open_table($Tree_handle, $Table,
                        $Table_name, SR_METADATA);
($rc == 0) || error_exit($rc);

# Add the table to the cleanup hash
push @{$Cleanup{Tables}}, $Table_handle;

                
# Call to C API to delete columns. Report on success or failure.
$Trace && print STDERR "Calling CT::SR::delete_columns\n";
$rc = CT::SR::delete_columns($Table_handle, \@ARGV, scalar(@ARGV));
$Trace && 
    print STDERR "CT::SR::delete_columns return code: $rc\n";
$rc = error_check("sr_delete_columns", $rc, $Table_name);
($rc == 0) || error_exit($rc);


# Clean up session  
$rc = clean_session($Tree_handle, $Mount_point, $Table_handle);

# Blank out the Cleanup hash before this call - there was an
# error already trying to do that!
%Cleanup = ();
($rc == 0) || error_exit($rc);

# Exit with the least non-zero return code
exit $rc;

#--------------------------------------------------------------------#
# End Main Code                                                      #
#--------------------------------------------------------------------#


#--------------------------------------------------------------------#
# parse_cmd_line:                                                    #
#   Uses getopts() to grab flags on the command line                 #
#                                                                    #
# Return values:                                                     #
#   $local_rc - local return code                                    #
#   $table_name - table name to be added                             #
#                                                                    #
# Global variables modified:                                         #
#   $Trace             output   True (-T) turn Trace mode on.        #
#   $Verbose           output   True (-V) turn Verbose mode on.      #
#--------------------------------------------------------------------#
sub parse_cmd_line
{
my $local_rc = 0;
my $table_name = "";
my %opts = ();

if (getopts('hTV', \%opts) == 0) {       # parse input flags
    # Return Error parsing flags - add a message here, too.
    printCEMsg("EMsgSRcliInvalidFlag");
    print_usage();
    return SR_CLI_BAD_FLAG;
}                  

if (defined $opts{h}) {             # print usage and exit
    print_usage();
    exit(0);                        # exit quickly
}

# Set Trace flag if requested
if (defined $opts{T}) {
    $Trace = $TRUE;                 # -T turns trace on 
}

# Set Verbose flag if requested
if (defined $opts{V}) {         
    $Verbose = $TRUE;               # -V turns verbose mode on
}

# Get table name from input.
$table_name = shift @ARGV;
if ((!$table_name) || ($table_name =~ /=/)) {
    printCEMsg("EMsgSRcliNoTableName");
    print_usage();
    return SR_CLI_BAD_OPERAND;
}

# If no column given to be removed, report an error
if (!@ARGV) {
    printCEMsg("EMsgSRcliNoColumnData");
    print_usage();
    return SR_CLI_BAD_OPERAND;
}

return ($local_rc, $table_name);
}   # end parse_cmd_line


#--------------------------------------------------------------------#
# error_check:                                                       #
#   Checks the return code from the SR function.  If an error is     #
#   detected appropriate error messages will be displayed and        #
#   SR CLI return code set.                                          #
#                                                                    #
# Parameters:                                                        #
#   $sr_function  - Name of the SR function that was called and      #
#                   whose error code we are checking.                #
#   $sr_rc        - SR function return code.                         #
#   $table_name   - Name of the SR table.                            #
#                                                                    #
# Return values:                                                     #
#   None.                                                            #
#                                                                    #
# Global References:                                                 #
#   None.                                                            #
#--------------------------------------------------------------------#
sub error_check
{
my ($sr_function, $sr_rc, $table_name) = @_;
my $rc = 0;

if ($sr_rc != 0){ 
    if ($sr_rc == SR_NO_PERMISSION) {
        printEMsg("EMsgrmsrcolNoPermission", $table_name);
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_NO_TABLE) {
        printCEMsg("EMsgSRcliNoTable", $table_name);
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_CONNECTION_LOST) {
        printCEMsg("EMsgSRcliConnectionLost");
        $rc = SR_CLI_REGISTRY_ERROR;
    }
    elsif ($sr_rc == SR_INVALID_COLUMN) {
        printEMsg("EMsgrmsrcolInvalidColumn", $table_name);
        $rc = SR_CLI_USER_ERROR;
    }
    else {
        # Print this message regardless to record the SR error code
        printEMsg("EMsgrmsrcolErrorRemovingColumns", $table_name);
        printCEMsg("EMsgSRcliSRCommandFailure", $sr_function, $rc);
        $rc = SR_CLI_REGISTRY_ERROR;
    }
} 

return ($rc);
}   # end error_check


#--------------------------------------------------------------------#
# print_usage : print the usage statement (syntax) to stdout.        #
#   See this command's prologue syntax section for current usage.    #
#--------------------------------------------------------------------#
sub print_usage
{
printIMsg("IMsgrmsrcolUsage");
}   # end print_usage


#--------------------------------------------------------------------#
# End File                                                           #
#--------------------------------------------------------------------#
